﻿using Nop.Core;
using Nop.Plugin.Widgets.AllInOne.Services;
using Nop.Plugin.Widgets.AllInOne.Domain;
using Nop.Plugin.Widgets.AllInOne.Models;
using Nop.Services.Configuration;
using Nop.Services.Localization;
using Nop.Services.Stores;
using Nop.Web.Framework;
using Nop.Web.Framework.Controllers;
using Nop.Web.Framework.Kendoui;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web.Mvc;

namespace Nop.Plugin.Widgets.AllInOne.Controllers
{
    public class WidgetsAllInOneController : BasePluginController
    {
        #region Fields
        private readonly IAllInOneService _allInOneService;
        private readonly IWorkContext _workContext;
        private readonly IStoreContext _storeContext;
        private readonly IStoreService _storeService;
        private readonly ISettingService _settingService;
        private readonly ILocalizationService _localizationService;
        private readonly IWebHelper _webHelper;
        #endregion

        #region Constructors

        public WidgetsAllInOneController(IAllInOneService allInOneService,
            IWorkContext workContext,
            IStoreContext storeContext, IStoreService storeService,
            ISettingService settingService,
            ILocalizationService localizationService, IWebHelper webHelper
            )
        {
            this._allInOneService = allInOneService;
            this._workContext = workContext;
            this._storeContext = storeContext;
            this._storeService = storeService;
            this._settingService = settingService;
            this._localizationService = localizationService;
            this._webHelper = webHelper;
        }

        #endregion

        #region Utilities
        protected AllInOneModel PrepareAllInOneModel(AllInOneObject allInOne)
        {
            var allInOneModel = new AllInOneModel()
            {
                Id = allInOne.Id,
                Name = allInOne.Name,
                HtmlCode = allInOne.HtmlCode,
                HtmlCodeExtra = allInOne.HtmlCodeExtra,
                WidgetZone = allInOne.WidgetZone,
                Published = allInOne.Published,
                DisplayOrder = allInOne.DisplayOrder,
                cssFileList = allInOne.cssFileList,
                jsFileList = allInOne.jsFileList,
            };
            return allInOneModel;
        }

        #endregion

        #region Admin

        public ActionResult Index()
        {
            return RedirectToAction("List");
        }

        public ActionResult List()
        {
            return View("~/Plugins/Widgets.AllInOne/Views/List.cshtml");
        }

        [HttpPost]
        public ActionResult List(DataSourceRequest command, AllInOneModel model)
        {
            var allInOnes = _allInOneService.GetAllInOnes("", command.Page - 1, command.PageSize);

            var tmp = new List<AllInOneModel>();
            foreach (var allInOne in allInOnes)
            {

                tmp.Add(PrepareAllInOneModel(allInOne));
            }

            var tmp2 = tmp.PagedForCommand(command);
            var gridModel = new DataSourceResult
            {
                Data = tmp2,
                Total = tmp2.Count()
            };

            return new JsonResult
            {
                Data = gridModel
            };
        }

        #region Create / Edit / Delete

        public ActionResult Create()
        {
            var model = new AllInOneModel();
            model.Published = true;

            return View("~/Plugins/Widgets.AllInOne/Views/Create.cshtml", model);
        }

        [HttpPost, ParameterBasedOnFormName("save-continue", "continueEditing")]
        public ActionResult Create(AllInOneModel model, bool continueEditing)
        {
            if (ModelState.IsValid)
            {
                var allInOne = new AllInOneObject()
                {
                    Id = model.Id,
                    Name = model.Name,
                    WidgetZone = model.WidgetZone,
                    Published = model.Published,
                    DisplayOrder = model.DisplayOrder,
                    HtmlCode = model.HtmlCode,
                    HtmlCodeExtra = model.HtmlCodeExtra,
                    jsFileList = model.jsFileList,
                    cssFileList = model.cssFileList,
                };
                _allInOneService.InsertAllInOne(allInOne);

                SuccessNotification(_localizationService.GetResource("Plugins.Widgets.AllInOne.Added"));
                return continueEditing ? RedirectToAction("Edit", new { id = allInOne.Id }) : RedirectToAction("List");
            }

            return View(model);
        }

        public ActionResult Edit(int id)
        {
            var allInOne = _allInOneService.GetAllInOneById(id);
            if (allInOne == null)
                //No page found with the specified id
                return RedirectToAction("List");
            var model = PrepareAllInOneModel(allInOne);

            return View("~/Plugins/Widgets.AllInOne/Views/Edit.cshtml", model);
        }

        [HttpPost, ParameterBasedOnFormName("save-continue", "continueEditing")]
        public ActionResult Edit(AllInOneModel model, bool continueEditing)
        {
            var allInOne = _allInOneService.GetAllInOneById(model.Id);
            if (allInOne == null)
                //No page found with the specified id
                return RedirectToAction("List");

            if (ModelState.IsValid)
            {
                allInOne.Name = model.Name;
                allInOne.WidgetZone = model.WidgetZone;
                allInOne.Published = model.Published;
                allInOne.DisplayOrder = model.DisplayOrder;
                allInOne.HtmlCode = model.HtmlCode;
                allInOne.HtmlCodeExtra = model.HtmlCodeExtra;
                allInOne.jsFileList = model.jsFileList;
                allInOne.cssFileList = model.cssFileList;

                _allInOneService.UpdateAllInOne(allInOne);

                SuccessNotification(_localizationService.GetResource("Plugins.Widgets.AllInOne.Updated"));
                return continueEditing ? RedirectToAction("Edit", allInOne.Id) : RedirectToAction("List");
            }

            return View(model);
        }

        [HttpPost]
        public ActionResult Delete(int id)
        {
            var allInOne = _allInOneService.GetAllInOneById(id);
            if (allInOne == null)
                //No page found with the specified id
                return RedirectToAction("List");

            _allInOneService.DeleteAllInOne(allInOne);

            SuccessNotification(_localizationService.GetResource("Plugins.Widgets.AllInOne.Deleted"));
            return RedirectToAction("List");
        }

        #endregion
        #endregion

        [AdminAuthorize]
        [ChildActionOnly]
        public ActionResult Configure()
        {
            return View("~/Plugins/Widgets.AllInOne/Views/Configure.cshtml");
        }
 
        [ChildActionOnly]
        public ActionResult PublicInfo(string widgetZone)
        {
            var allInOnes = _allInOneService.GetAllInOnesByWidgetZones(widgetZone);
            var model = new PublicInfoModel();
            foreach (var item in allInOnes)
            {
                string htmlCode = item.HtmlCode;
                //add extea code
                if (!string.IsNullOrEmpty(item.HtmlCodeExtra))
                {
                    htmlCode += item.HtmlCodeExtra;
                }
                model.HtmlCodes.Add(htmlCode);

                if (!string.IsNullOrEmpty(item.cssFileList))
                {
                    var CssFiles = new List<string>(item.cssFileList.Split(','));
                    var supportRtl = _workContext.WorkingLanguage.Rtl;
                    foreach (var css in CssFiles)
                    {
                        var fileName = css + ((supportRtl) ? ".rtl.css" : ".css");
                        var filePath = Path.Combine(_webHelper.MapPath("~/Plugins/Widgets.AllInOne/Content/"),fileName );
                        if (System.IO.File.Exists(filePath))
                        {
                            model.CssFiles.Add(fileName);
                        }                       
                    }
                }

                if (!string.IsNullOrEmpty(item.jsFileList))
                {
                    var JFiles = new List<string>(item.jsFileList.Split(','));
                    foreach (var js in JFiles)
                    {
                         var filePath = Path.Combine(_webHelper.MapPath("~/Plugins/Widgets.AllInOne/Content/"), js);
                         if (System.IO.File.Exists(filePath))
                         {
                             model.JFiles.Add(js);
                         }
                    }
                }
            }

            return View("~/Plugins/Widgets.AllInOne/Views/PublicInfo.cshtml", model);
        }
    }
}